<?php

namespace wechat;


class WechatController
{
    private WechatService $wechatPayService;
    public function __construct($sub_mch_id, $secret)
    {
        $this->wechatPayService = new WechatService($sub_mch_id, $secret);
    }

    public function unifiedorder($data): array
    {
        $data = [
            'body' => $data['body'],
            'out_trade_no' => $data['order_id'],
            'total_fee' => function_exists('bcmul') ? bcmul($data['amount'], 100) : $data['amount'] * 100,
            'notify_url' => "http://vip.juanboss.com/api/separate_accounts/notify",
            'trade_type' => 'JSAPI',
            'openid' => $data['openid'],
            'sub_mch_id' => $data['sub_mch_id'], //支付子商户号
            'profit_sharing' => 'Y',
        ];
        return $this->wechatPayService->unifiedorder($data);
    }

    public function handlePaidNotify($data)
    {
        return $this->wechatPayService->handlePaidNotify($data);
    }

    public function share($data): ?array
    {
        return $this->wechatPayService->share($data);
    }

    /**
     * 绑定账号
     * @param $data
     * @return mixed
     */
    public function addReceiver($data)
    {
        return $this->wechatPayService->addReceiver($data);
    }

    /**
     * 绑定openid
     * @param $data
     * @return mixed
     */
    public function addReceiverOpenid($data)
    {
        return $this->wechatPayService->addReceiverOpenid($data);
    }

    public function unify($sub_mch_id)
    {
        $order_id = date("YmdHis") . mt_rand(100000, 999999);
        $data['amount'] = 1;
        $data = [
            'body' => "商户支付测试",
            'out_trade_no' => $order_id,
            'total_fee' => function_exists('bcmul') ? bcmul($data['amount'], 100) : $data['amount'] * 100,
            'notify_url' => 'http://vip.juanboss.com/api/separate_accounts/notify',
            'trade_type' => 'NATIVE',
            'sub_mch_id' => $sub_mch_id,
            'profit_sharing' => 'Y',
        ];
        return $this->wechatPayService->unify($data);
    }

    public function notify($data)
    {
        return $this->wechatPayService->notify($data);
    }
    public function separate_accounts($data,$transaction_id){
        $arr = [];
        foreach ($data as $datum) {
            $order_id = $datum->order_id;
            $arr['receivers'][] = [
                'type' => $datum['type'],
                'amount' => $datum['amount'],
                'account' => $datum['account'],
                'description' => $datum['description']
            ];
        }
        $arr['order_id'] = $order_id;
        $arr['transaction_id'] = $transaction_id;
        return $this->wechatPayService->separate_accounts($arr);
    }

}